import uuid
import random
from dateutil.relativedelta import relativedelta
from flask.globals import current_app

from datetime import datetime, timedelta
from pymongo import results
from pymongo.results import InsertManyResult
from lina.mongodb import db, truncate, insert_batch, insert
from lina.models import Case, Phase, Task, Comment
from lina.utils import get_name


def fake_user():
    users = [{
        "id": 4,
        "union_id": 'oV8g6wF5__aHpAQPncIX0fQXiNUw',
        "open_id": 'ok1jF5IzzHuXcBinI-8Sq0PntK2c',
        "gender": 0,
        "nickName": '光哥',
        "fullName": "guangge show time",
        "telNumber": "",
        "avatar": "",
        "birthday": ""
    }]

    pass


def fake_tag():
    table_name = 'tag'
    tags = []

    truncate(table_name)

    tags.append({
        "key": "保险公司",
        "theme": "primary",
        "value": ["人保", "平安", "太保", "人寿财险",
                  "大地", "安邦", "华泰", "中华联合", "天安", "永安", "浙商", "国元"]
    })

    tags.append({
        "key": "责任划分",
        "theme": "success",
        "value": ["主责", "次责", "同责", "无责"]
    })

    tags.append({
        "key": "办案警察",
        "theme": "error",
        "value": ["周木琪", "程佳洁", "蔡超", "蔡梦思", "罗梓桐", "黄翊恒", "程加胤"]
    })

    tags.append({
        "key": "伤情概要",
        "theme": "warning",
        "value": ["半月板", "精鉴", "不够残", "10级", "肋骨", "肩袖损伤"]
    })

    return insert(table_name, tags)


def fake_case(phase_ids):
    table_name = 'case'
    case_to_append = []

    # 获取所有的tag，用来随机插入
    all_tags = []
    for tag_array in db()['tag'].find():
        current_app.logger.info(tag_array)
        theme = tag_array["theme"]
        for tag in tag_array["value"]:
            all_tags.append({"type": theme, "value": tag})

    # 生成所有案件标题，用来随机插入

    """ 案件 """
    truncate(table_name)

    for phase_id in phase_ids:
        case_per_phase = random.randint(3, 15)

        while case_per_phase > 0:

            now = datetime.now()

            # act_random = random.randint(60, 300)
            # court_random = random.randint(2, 40)

            # actdate = now + timedelta(days=0-random.randint(60, 300))
            # court_date = now + timedelta(days=random.randint(2, 40))

            item_count = random.randint(0, 7)
            tags = random.sample(all_tags, item_count)

            title = get_name()
            desc = "desc" .join(str(uuid.uuid4()).split('-'))
            case = Case(phase_id=phase_id, title=title, desc=desc, tags=tags)
            case.actdate = now + timedelta(days=0-random.randint(60, 300))
            case.courtdate =  now + timedelta(days=random.randint(2, 40))

            case_to_append.append(case.__dict__)
            case_per_phase = case_per_phase-1

    return insert_batch(table_name, case_to_append).inserted_ids


def fake_comment(case_ids):
    table_name = 'comment'
    comment_to_append = []

    comments = ["一生所获，不如一夜星空。",
                "愿你走出半生，归来仍是少年。",
                "在遇见你的那一刻，浩瀚众星，皆降为尘。",
                "诗人喜欢远方和流浪，我偏爱你与人间烟火。",
                "最美的不是下雨天，是曾与你躲过雨的屋檐。",
                "愿世界化为沧海，愿你我归于初见。",
                "也许，就在那一刻里，梦境还在，柔情亦在。",
                "阳光温热，岁月静好，你还不来，我怎敢老去？",
                "往后余生，风雪是你，平淡是你，心底温柔也是你。",
                "众里寻他千百度，蓦然回首，那人却在灯火阑珊处。",
                "若是这世界的等待，都能如风吹花落般默契，该多好啊。",
                "是不是月老和孟婆曾是情人，一个牵了情丝，一个断了红尘。",
                "日月是你，星辰是你，山川是你，江流是你，余生万物都是你。",
                "思念在流年里沉淀，辗转，是谁的歌声依旧打动着彼此的心？",
                "人有时被拥裹，只能顺着。不过，到了分流的时候，还得往回走。",
                "悄悄地我走了，正如我悄悄的来；我挥一挥衣袖，不带走一片云彩。--徐志摩《再别康桥》",
                "你是我，千年又千年的凝望。纵然千帆过尽了，切切因你，情思依依，眷恋如昔。",
                "愿时光能缓，愿故人不散；愿你惦念的人能和你道晚安，愿你独闯的日子里不觉得孤单。",
                "细碎的声音，如羞涩的蓓蕾，夜暮花影，清浅六月，寂寂流年，拢一阙清绝，归隐在宋词里。",
                "总有些人遗落在红尘，牵动我的心，熟悉而陌生的歌谣，在记忆深处低回，风华是一指流砂，苍老是一段年华。随你走在天际，看繁花满地。褪尽风华，我依然在彼岸守护你。"]

    for case_id in case_ids:
        comment_per_case = random.randint(0, 5)
        while comment_per_case > 0:
            content = random.choice(comments)
            comment = Comment(case_id, content)
            comment_to_append.append(comment.__dict__)
            comment_per_case = comment_per_case-1

    return insert_batch(table_name, comment_to_append).inserted_ids


def fake_phase():
    table_name = 'phase'
    phase_list = ["住院", "准备阶段", "等鉴定报告",
                  "准备起诉资料", "已交律师", "法院已立案", "重新鉴定", "开庭", "已上诉", "办款中"]

    truncate(table_name)

    index = 0
    obj_list = []
    for phase_name in phase_list:
        phase_str = Phase(phase_name, index)
        index = index + 1
        obj_list.append(phase_str.__dict__)

    return insert_batch(table_name, obj_list).inserted_ids


def fake_task(inserted_case_ids):
    table_name = 'task'
    task_names = ['拿病历', '做鉴定', '准备资料', '递交律师', '开庭', '拿鉴定报告']

    truncate(table_name)

    task_to_add = []
    for case_id in inserted_case_ids:
        for task_name in task_names:
            task = Task(case_id=case_id, title=task_name,
                        expired_time=datetime.now() + timedelta(days=30))
            task_to_add.append(task.__dict__)
    return insert_batch(table_name, task_to_add)
